const Controller = require('../core/base_controller');

const assert = require('assert')

class AppController extends Controller {

    // 分页查询客户信息
    async index() {
        const { service: { customer }, app: { model: { Customer } } } = this
        let param = this.param
        let { limit, page, where } = param
        if (!limit) {
            limit = 10
        }
        if (!page) {
            page = 1
        }
        //计算offset
        let offset = (page - 1) * limit

        let ret = await customer.page({
            where,
            limit,
            offset,
        });
        this.success(ret)
    }

    /**
     * 保存客户信息
     * 
     * @memberof AppController
     */
    async save() {
        let { app, param } = this
        param.created_userid = this.ctx.state.user.userid
        let ret = await app.table('customer').save(param)
        //推送信息给指定人
        await this.app.dtalk.rest.sendMessage({
            msgtype: 'text',
            agent_id: 130515746,
            userid_list: param.userid,
            to_all_user: false,
            msgcontent: JSON.stringify({
                "content": `温馨提示：新建客户单位【${param.dept}】 初步需求:${param.remark}`
            })
        })

        this.success(ret)
    }

    async remove() {
        let { app, param, param: { id: customer_id } } = this
        //删除客户
        let ret = await app.table('customer').delete(param)
        //删除联系人数据
        ret = await app.table('contact').deleteBy({
            customer_id
        })
        //删除批次信息
        ret = await app.table('batch').deleteBy({
            customer_id
        })
        //删除批次产品信息
        ret = await app.table('batch_product').deleteBy({
            customer_id
        })

        this.success()
    }

    //获取客户签约信息
    async getCustomerSaleInfo() {
        const { customer_id } = this.param
        assert(customer_id, '未找到客户信息')
        let ret = this.service.customer.getCustomerSaleInfo(this.param)
        this.success(ret)
    }

}
module.exports = AppController;
